<template>
	<view class="widthdraw-page">
		<view class="container">
			<template v-if="isBindBank">
				<view class="balance">
					<text>{{ $t('Page.user.kyye') }}</text>
					<image class="coin-icon" src="@/static/coin.png"></image>
					<text>{{ userMoney }}</text>
				</view>
				<view class="title">{{ $t('Page.user.tkje') }}</view>
				<view class="rechargeInput">
					<image class="coin-icon" src="@/static/coin.png"></image>
					<input class="uni-input" type="number" @focus="isFocus = true" @blur="isFocus = false"
						v-model="withdrawAmount" />
					<view :class="['bottom-line', isFocus ? 'show-line' : 'hide-line']"></view>
				</view>
				<view class="progressBox">
					<view class="">
						{{ $t('Page.user.cosc') }}
					</view>
					<progress :percent="userInfo.withdrawseting.progress" backgroundColor="#2b333b"
						activeColor="#1fff20" :show-info="true"></progress>
				</view>
				<view class="noParBox">
					<checkbox-group @change="checkboxChange">
						<label>
							<checkbox value="cb" color="#FFFFFF" checked disabled />{{ $t('Page.user.sytys') }}
						</label>
					</checkbox-group>
				</view>
				<view class="fee-wrap">
					{{ $t('Page.user.fy')}} :
					<text class="fee">{{ levelInfo.withdraw_rate }}% </text>
					({{ $t('Page.user.njsd') }} {{ realAmount }})
				</view>
				<view>
					<view>{{ $t('Page.user.copi') }} : {{ userInfo.gametotal }}</view>
					<view>{{ $t('Page.user.cofl') }} :{{ userInfo.withdrawseting.can_withdraw.toFixed(2) }}</view>
					<!-- <view>{{ $t('Page.user.cosc') }} : {{ userInfo.withdrawseting.progress }}% </view> -->
					<view>{{ $t('Page.user.coxy') }} :
						{{ (userInfo.withdrawseting.can_withdraw - userInfo.gametotal).toFixed(2) }}
					</view>
				</view>
				<view class="submit-wrap">
					<waves class="depositBtn" @onTap="handeleWithdraw" @keyup.enter="handeleWithdraw">
						{{ $t('Page.user.tj') }}
					</waves>
				</view>
			</template>
			<template v-else>
				<view class="noBind">
					<uni-icons type="info-filled" size="30" color="#4caf50"></uni-icons>
					<text>{{ $t('Page.user.qxcrzj') }}</text>
				</view>
			</template>
		</view>
		<view class="widthdraw-record" v-if="isBindBank">
			<text class="record-tips" @click="toRecord">{{ $t('Page.user.tbjl') }}</text>
			<uni-icons class="record-icon" custom-prefix="iconfont" type="icon-dingdan" size="25" color="#fff"
				@click="toRecord"></uni-icons>
		</view>
		<uni-transition ref="vipPopup" mode-class="fade" :show="isShow">
			<responsivePopup @closePopup="closePopup">
				<view class="header">
					<waves class="title">
						<uni-icons class="add-card" custom-prefix="iconfont" type="icon-tianjiayinhangka-mianxing"
							color="#cdcde5" size="26"></uni-icons>
						<text>Add Bank Account</text>
					</waves>
					<uni-icons class="forClose" type="closeempty" size="24" color="#fff"
						@click="closePopup"></uni-icons>
				</view>
				<uni-forms ref="bindBankRef" :rules="bindBankRules" :modelValue="bankInfo" validateTrigger="blur"
					label-position="top">
					<uni-forms-item label-width="200px" name="phone" label="Phone Number">
						<uni-easyinput maxlength="30" :styles="styles" primaryColor="#33C38F"
							v-model.trim="bankInfo.phone" :clearable="false" />
					</uni-forms-item>
					<uni-forms-item label-width="200px" name="cpf" label="CPF">
						<uni-easyinput maxlength="30" :styles="styles" primaryColor="#33C38F"
							v-model.trim="bankInfo.cpf" :clearable="false" />
					</uni-forms-item>
					<uni-forms-item label-width="200px" name="name" label="Name">
						<uni-easyinput maxlength="30" :styles="styles" primaryColor="#33C38F"
							v-model.trim="bankInfo.name" :clearable="false" />
					</uni-forms-item>
					<uni-forms-item label-width="200px" name="email" label="Email">
						<uni-easyinput maxlength="30" :styles="styles" primaryColor="#33C38F"
							v-model.trim="bankInfo.email" :clearable="false" />
					</uni-forms-item>
					<uni-forms-item label-width="200px" name="pix" label="PIX">
						<uni-easyinput maxlength="30" :styles="styles" primaryColor="#33C38F"
							v-model.trim="bankInfo.pix" :clearable="false" />
					</uni-forms-item>
					<view class="submit-wrap">
						<waves class="depositBtn" @onTap="confirm('bindBankRef')"> Confirm </waves>
					</view>
				</uni-forms>
			</responsivePopup>
		</uni-transition>
	</view>
</template>

<script>
	import {
		sendMessage
	} from '@/api/websocket.js'
	import {
		Debounce
	} from '@/utils/common.js'
	import {
		validarCPF
	} from '@/utils/function/reg.js'
	import {
		fomatFloat
	} from '@/utils/function/index.js'
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				withdrawAmount: 0,
				feeAmount: 0,
				receiveAmount: 0,
				isFocus: false,
				userWallet: {},
				userInfo: {},
				withdrawseting: {},
				levelInfo: {},
				isBindBank: false,
				isPC: false,
				styles: {
					borderColor: '#2e363f',
					color: '#fff',
					backgroundColor: '#242A32'
				},
				bindBankRules: {
					phone: {
						rules: [{
								required: true,
								errorMessage: 'Please enter phone number'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length < 10 || value.length > 13) {
										callback('Please enter a 10-13 digit phone number')
									}
									return true
								}
							}
						]
					},
					cpf: {
						rules: [{
								required: true,
								errorMessage: 'Please fill in CPF'
							},
							{
								validateFunction: (rule, value, data, callback) => {
									if (!validarCPF(value)) {
										callback('CPF is incorrect')
									}
									return true
								}
							}
						]
					},
					name: {
						rules: [{
							required: true,
							errorMessage: 'Please fill in your name'
						}]
					},
					email: {
						rules: [{
								required: true,
								errorMessage: 'Please fill in the email address'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
									if (!emailRegex.test(value)) {
										callback('Incorrect email format')
									}
									return true
								}
							}
						]
					},
					pix: {
						rules: [{
							required: true,
							errorMessage: 'Please fill in PIX'
						}]
					}
				},
				bankInfo: {
					phone: '',
					cpf: '',
					name: '',
					email: '',
					pix: ''
				},
				isShow: false
			}
		},
		computed: {
			...mapState({
				userMoney: state => state.app.userMoney
			}),
			isRangeWithdraw() {
				return parseFloat(this.withdrawAmount) < this.withdrawseting.minprice ||
					parseFloat(this.withdrawAmount) > this.withdrawseting.maxprice
			},
			remainWithdrawLimit() {
				return parseFloat(this.levelInfo.withdraw_total) -
					parseFloat(this.withdrawseting.withdraw_dealmoney)
			},
			remainWithdrawNum() {
				return this.levelInfo.withdraw_num - this.withdrawseting.withdraw_dealnum
			},
			realAmount() {
				const rate = Number(this.levelInfo.withdraw_rate)
				return this.withdrawAmount - fomatFloat((this.withdrawAmount * rate) / 100, 2)
			}
		},
		created() {
			this.getWalletInfo()
		},

		methods: {
			// 使用 Debounce 修饰符，实现防抖效果
			submit: Debounce(function() {
				const {
					ADDBANK
				} = this.$api
				sendMessage({
					flag: ADDBANK,
					content: this.bankInfo
				})
				uni.$once(ADDBANK, (res) => {
					const {
						code,
						data,
						msg
					} = res
					console.log("res: ", res);
					this.showToast(msg)
					if (code === 1) {
						this.getWalletInfo()
					}
				})
			}, 500),
			confirm(ref) {
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
					this.submit()
				}).catch(err => {
					console.log('err', err);
				})
			},

			closePopup() {
				this.isShow = false
			},

			getWalletInfo() {
				const {
					USERWALLET
				} = this.$api
				sendMessage({
					flag: USERWALLET
				})
				uni.$once(USERWALLET, (res) => {
					const {
						code,
						data
					} = res
					if (code === 1) {
						this.userInfo = data.userinfo
						this.withdrawseting = data.userinfo.withdrawseting
						this.levelInfo = data.userinfo.level
						this.isBindBank = data.userinfo.bank instanceof Object
						this.isShow = !this.isBindBank
					}
				})
			},

			showToast(title) {
				uni.showToast({
					icon: 'none',
					title
				})
			},

			// 校验金额是否合法
			checkMoney() {
				const withdrawAmount = parseFloat(this.withdrawAmount)
				console.log("withdrawAmount: ", withdrawAmount);
				console.log("this.remainWithdrawNum: ", this.remainWithdrawNum);
				if (!withdrawAmount) { //未输入提现金额
					this.showToast('Please enter the withdrawal amount')
					return false
				} else if (this.remainWithdrawNum <= 0) { //提现次数用完
					this.showToast('The number of withdrawals on that day has been used up')
					return false
				} else if (this.remainWithdrawLimit < withdrawAmount) { //提现额度不足 
					this.showToast('The withdrawal limit on that day is insufficient')
					return false
				} else if (this.remainWithdrawLimit <= 0) { //提现额度已用完
					this.showToast('The withdrawal limit on that day has been used up')
					return false
				} else if (withdrawAmount > this.userInfo.money) { //提现金额大于账户总额 
					this.showToast('Insufficient account balance')
					return false
				} else if (this.isRangeWithdraw) { //提现金额不在提现金额范围内
					this.showToast(
						`The amount range must be between ${this.withdrawseting.minprice}~${this.withdrawseting.maxprice}`
					)
					return false
				} else {
					return true
				}
			},


			// 使用 Debounce 修饰符，实现防抖效果
			handeleWithdraw: Debounce(function() {
				console.log("this.checkMoney(): ", this.checkMoney());
				if (!this.checkMoney()) return;
				const {
					WITHDRAW
				} = this.$api
				sendMessage({
					flag: WITHDRAW,
					content: {
						price: this.withdrawAmount
					}
				})
				uni.$once(WITHDRAW, (res) => {
					this.showToast(res.msg)
				})
			}, 500),

			toRecord() {
				uni.navigateTo({
					url: `/pages/user/transactions/transactions?index=1`
				})
			}

		}
	}
</script>

<style lang="scss" scoped>
	.widthdraw-page {
		width: 100%;

		.container {
			width: calc(100% - 48px);
			margin: 0 auto;
			box-sizing: border-box;

			.noBind {
				width: 100%;
				display: flex;
				align-items: center;
				color: #4caf50;
				font-size: 14px;

				text {
					margin-left: 5px;
				}
			}

			.balance {
				width: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #4caf50;
				font-size: 14px;
				font-weight: 600;

				.coin-icon {
					width: 30px;
					height: 30px;
					margin: 0 5px;
				}
			}

			.title {
				color: #fff;
				margin-bottom: 10px;
			}

			.rechargeInput {
				width: 100%;
				border-radius: .75rem;
				display: flex;
				justify-content: space-between;
				align-items: center;
				background: #2b333b;
				height: 40px;
				position: relative;
				overflow: hidden;

				.coin-icon {
					width: 30px;
					height: 30px;
					margin-left: 10px;
				}

				.uni-input {
					color: #fff;
					font-size: 1.2rem;
					font-weight: 700;
					text-align: right;
					padding: 8px;
					height: 40px;
					background-color: transparent;
				}

				.bottom-line {
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 0;
					height: 2px;
					background-color: #fff;
					transition: all .25s;
				}

				.show-line {
					width: 100%;
				}

				.hide-line {
					width: 0;
				}
			}

			.progressBox {
				margin-top: 15px;
				border-radius: 4px;
				display: flex;
				flex-direction: column;

				/deep/.uni-progress {
					border-radius: inherit;
				}

				/deep/.uni-progress-bar {
					border-radius: inherit;
					height: 1em !important;
				}

				/deep/.uni-progress-inner-bar {
					border-radius: inherit;
				}
			}

			.noParBox {
				margin-top: 24px;
				width: 100%;
				border-radius: .5rem;
				height: 40px;
				color: #fff;
				display: flex;
				align-items: center;
				opacity: .6;

				/deep/ .uni-checkbox-input {
					transform: scale(0.9);
					border: 2px solid #000000;
					border-radius: 2px;
					background-color: transparent;
				}

				/deep/ .uni-checkbox-input-checked {
					border: 2px solid #00e701;
					background-color: #33c38f;
				}
			}

			.fee-wrap {
				color: #fff;

				.fee {
					margin: 0 5px;
					color: #4caf50;

				}
			}

			.submit-wrap {
				width: 100%;
				display: flex;
				justify-content: center;
				margin: 24px auto;
				color: #fff;

				.depositBtn {
					color: #fff;
					font-size: 14px;
					color: #fff;
					background: #f44336;
					width: 41.6667%;
					text-align: center;
					font-weight: 700;
					height: 52px;
					line-height: 52px;
					border-radius: .5rem;
					box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2), 0 2px 2px rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.12);
				}
			}
		}

		.widthdraw-record {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			background-color: #2b333b;
			padding: 8px;
			height: 56px;

			.record-tips {
				color: #177ddc;
				text-decoration: underline;
				cursor: pointer;
				margin-left: 16px;
			}

			.record-icon {
				cursor: pointer;
			}
		}
	}

	.header {
		border-radius: inherit;
		padding: 8px 8px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.title {
			border-radius: 28px;
			background: #1e232a;
			padding: 4px 16px 4px 10px;
			min-height: 2.572em;
			color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			font-weight: 700;

			text {
				margin-left: 5px;
			}
		}

		.forClose {
			cursor: pointer;
		}
	}

	.uni-forms {
		width: 500px;
		padding: 0 15px;

		/deep/.uni-forms-item__label {
			color: #adadc2;
			font-weight: 700;
			font-size: 14px;
		}

		/deep/.uni-easyinput__content {
			&:hover {
				border: 2px solid #000 !important;
			}
		}

		.submit-wrap {
			width: 100%;
			display: flex;
			justify-content: center;
			margin: 24px auto;
			color: #fff;

			.depositBtn {
				color: #fff;
				font-size: 14px;
				color: #fff;
				background: #33c38f;
				width: 100%;
				text-align: center;
				font-weight: 700;
				height: 52px;
				line-height: 52px;
				border-radius: .2rem;
				box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2), 0 2px 2px rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.12);
			}
		}
	}

	@media screen and (max-width: 768px) {
		.uni-forms {
			width: 100vw !important;
		}
	}
</style>